﻿using System;
using System.Web.Mvc;
using System.Text;

namespace TNPTN.Utility
{
    /// <summary>
    /// Log Utility class
    /// Author: jabraok
    /// </summary>
    public static class Log
    {
        /// <summary>
        /// Write Log
        /// </summary>
        /// <param name="ex">Exception</param>
        public static void WriteLog(Exception ex)
        {
            //GET logger
            log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            //Error content
            StringBuilder builder = new StringBuilder(Environment.NewLine);
            builder.AppendLine()
                    .AppendLine("--------------------------------")
                    .AppendFormat("Message:\t{0}", ex.Message)
                    .AppendLine()
                    .AppendFormat("Source:\t{0}", ex.Source)
                    .AppendLine()
                    .AppendFormat("Target:\t{0}", ex.TargetSite)
                    .AppendLine()
                    .AppendFormat("Type:\t{0}", ex.GetType().Name)
                    .AppendLine()
                    .AppendFormat("Stack:\t{0}", ex.StackTrace);
            if (ex.InnerException != null)
            {
                builder.AppendLine()
                        .AppendFormat("InnerException:\t{0}", ex.InnerException.Message);
            }
            builder.AppendLine()
                    .AppendLine("--------------------------------")
                    .AppendLine();

            //Write log
            logger.Fatal(builder.ToString());
        }
    }

    /// <summary>
    /// Error Logger Attribute
    /// </summary>
    public class ErrorLoggerAttribute : HandleErrorAttribute
    {
        /// <summary>
        /// OnException
        /// </summary>
        /// <param name="filterContext">ExceptionContext</param>
        public override void OnException(ExceptionContext filterContext)
        {
            //Write Log
            Log.WriteLog(filterContext.Exception);
            base.OnException(filterContext);
        }
    }
}
       
